package com.leiqichao.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leiqichao.backend.entity.Tag;
import com.leiqichao.backend.mapper.TagMapper;
import com.leiqichao.backend.service.TagService;
import org.springframework.stereotype.Service;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Override
    public boolean createTag(Tag tag) {
        if (isSlugExists(tag.getSlug(), null)) {
            throw new IllegalArgumentException("标签别名已存在");
        }
        return save(tag);
    }

    @Override
    public boolean updateTag(Tag tag) {
        if (isSlugExists(tag.getSlug(), tag.getId())) {
            throw new IllegalArgumentException("标签别名已存在");
        }
        return updateById(tag);
    }

    /**
     * 校验标签slug唯一性
     */
    private boolean isSlugExists(String slug, Long excludeId) {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tag::getSlug, slug);
        if (excludeId != null) {
            queryWrapper.ne(Tag::getId, excludeId);
        }
        return count(queryWrapper) > 0;
    }
}